<!DOCTYPE html>
<html>
	<head>
		<title>订单列表</title>
		<meta charset="utf-8">
		<meta name="viewport" content="width=device-width,initial-scale=1,minimum-scale=1,maximum-scale=1,user-scalable=no" />
		<!-- 所有的 css & js 资源 -->
		<link rel="stylesheet" href="https://unpkg.com/element-ui@2.13.0/lib/theme-chalk/index.css">
		<link rel="stylesheet" href="../../static/sa.css">
		<script src="https://unpkg.com/vue@2.6.10/dist/vue.js"></script>
		<script src="https://unpkg.com/element-ui@2.13.0/lib/index.js"></script>
		<script src="https://unpkg.com/jquery@3.4.1/dist/jquery.js"></script>
		<script src="https://www.layuicdn.com/layer-v3.1.1/layer.js"></script>
		<script src="https://unpkg.com/axios/dist/axios.min.js"></script>
		<script src="../../static/sa.js"></script>
		<style>
			/* 订单网格布局 */
			.order-grid {
				display: grid;
				grid-template-columns: repeat(5, 1fr);
				gap: 12px;
				padding: 16px;
				max-width: 1600px;
				margin: 0 auto;
			}

			/* 订单卡片样式 */
			.order-card {
				border: 1px solid #ebeef5;
				border-radius: 8px;
				overflow: hidden;
				transition: all 0.3s ease;
				background: white;
				box-shadow: 0 1px 3px rgba(0,0,0,0.05);
				min-height: 260px;
				display: flex;
				flex-direction: column;
			}
			.order-card:hover {
				box-shadow: 0 4px 16px 0 rgba(0,0,0,0.12);
				transform: translateY(-2px);
				border-color: #409EFF;
			}

			/* 响应式调整 */
			@media (max-width: 1400px) {
				.order-grid {
					grid-template-columns: repeat(4, 1fr);
				}
			}

			@media (max-width: 1200px) {
				.order-grid {
					grid-template-columns: repeat(3, 1fr);
					gap: 10px;
				}
			}

			@media (max-width: 900px) {
				.order-grid {
					grid-template-columns: repeat(2, 1fr);
					gap: 8px;
				}
			}

			@media (max-width: 600px) {
				.order-grid {
					grid-template-columns: 1fr;
					gap: 12px;
					padding: 12px;
				}
				.order-card {
					min-height: auto;
				}
			}
			
			/* 订单头部 */
			.order-header {
				padding: 10px 12px;
				border-bottom: 1px solid #f0f0f0;
				display: flex;
				justify-content: space-between;
				align-items: center;
				background: linear-gradient(135deg, #f8f9fa 0%, #ffffff 100%);
				flex-shrink: 0;
			}
			.order-id {
				font-size: 12px;
				font-weight: 600;
				color: #303133;
				letter-spacing: 0.3px;
				white-space: nowrap;
				overflow: hidden;
				text-overflow: ellipsis;
				max-width: 140px;
			}
			.order-status {
				padding: 3px 8px;
				border-radius: 10px;
				font-size: 11px;
				font-weight: 500;
				white-space: nowrap;
			}
			.status-pending { background-color: #E6A23C; color: white; }
			.status-paid { background-color: #409EFF; color: white; }
			.status-awaiting_shipment { background-color: #909399; color: white; }
			.status-shipped { background-color: #67C23A; color: white; }
			.status-shipment { background-color: #67C23A; color: white; }
			.status-completed { background-color: #67C23A; color: white; }
			.status-cancelled { background-color: #F56C6C; color: white; }
			
			/* 订单内容 */
			.order-content {
				padding: 14px 16px;
			}
			
			/* 商品信息 */
			.product-info {
				display: flex;
				gap: 12px;
				margin-bottom: 12px;
			}
			.product-image {
				width: 80px;
				height: 80px;
				border-radius: 8px;
				overflow: hidden;
				box-shadow: 0 2px 8px rgba(0,0,0,0.1);
				flex-shrink: 0;
			}
			.product-image img {
				width: 100%;
				height: 100%;
				object-fit: cover;
			}
			.product-details {
				flex: 1;
			}
			.product-name {
				font-size: 14px;
				font-weight: 500;
				margin-bottom: 8px;
				color: #303133;
			}
			.product-price {
				color: #F56C6C;
				font-weight: 500;
				margin-bottom: 8px;
			}
			.product-meta {
				font-size: 12px;
				color: #909399;
			}
			.product-tags {
				margin: 6px 0;
				display: flex;
				gap: 6px;
				flex-wrap: wrap;
			}
			.product-tags .el-tag {
				font-size: 11px;
				height: 20px;
				line-height: 18px;
				border-radius: 10px;
			}
			
			/* 订单信息 */
			.order-info {
				margin-top: 15px;
				padding-top: 15px;
				border-top: 1px dashed #ebeef5;
			}
			.info-item {
				display: flex;
				justify-content: space-between;
				margin-bottom: 8px;
				font-size: 13px;
			}
			.info-label {
				color: #909399;
			}
			.info-value {
				color: #303133;
				font-weight: 500;
			}
			
			/* 订单底部 */
			.order-footer {
				padding: 15px;
				border-top: 1px solid #ebeef5;
				display: flex;
				justify-content: space-between;
				align-items: center;
			}
			.order-total {
				font-size: 16px;
				color: #F56C6C;
				font-weight: 500;
			}
			.order-actions {
				display: flex;
				gap: 10px;
			}
			
			/* 搜索面板 */
			.search-panel {
				background: white;
				padding: 20px;
				border-radius: 8px;
				box-shadow: 0 2px 12px 0 rgba(0,0,0,0.1);
				margin: 20px;
			}
			
			/* 分页样式 */
			.page-box {
				margin: 20px;
				text-align: center;
			}
		</style>
	</head>
	<body>
		<div id="app" class="vue-box">
			<!-- 检索区域 -->
			<div class="search-panel">
				<el-form :inline="true" size="small">
					<el-form-item label="订单ID">
						<el-input v-model="p.orderId" placeholder="请输入订单ID" clearable @keyup.enter.native="searchByIdAndStatus"></el-input>
					</el-form-item>
					<el-form-item label="订单状态">
						<el-select v-model="p.status" placeholder="请选择状态" clearable @change="searchByIdAndStatus">
							<el-option label="待支付" value="pending"></el-option>
							<el-option label="已支付" value="paid"></el-option>
							<el-option label="待发货" value="awaiting_shipment"></el-option>
							<el-option label="已发货" value="shipped"></el-option>
							<el-option label="发货中" value="shipment"></el-option>
							<el-option label="已取消" value="cancelled"></el-option>
							<el-option label="已完成" value="completed"></el-option>
						</el-select>
					</el-form-item>
					<el-form-item>
						<el-button type="primary" icon="el-icon-search" @click="searchByIdAndStatus">查询</el-button>
						<el-button type="info" icon="el-icon-refresh" @click="reset">重置</el-button>
					</el-form-item>
				</el-form>
			</div>
			
			<!-- 订单网格 -->
			<div class="order-grid" v-loading="loading">
				<div v-for="order in dataList" :key="order.id" class="order-card">
					<!-- 订单头部 -->
					<div class="order-header">
						<div class="order-id">订单号：{{ formatDisplayOrderId(order.orderId || order.id) }}</div>
						<span :class="['order-status', 'status-' + order.status]">
							{{ getStatusText(order.status) }}
						</span>
					</div>
					
					<!-- 订单内容 -->
					<div class="order-content">
						<!-- 商品信息 -->
						<div class="product-info">
							<div class="product-image" v-if="order.images && order.images.length > 0">
								<img :src="getFullImageUrl(order.images[0].image_url)" :alt="order.product && order.product.name || '商品图片'">
							</div>
							<div class="product-details">
								<div class="product-name">{{ order.product && order.product.name || '未知商品' }}</div>
								<div class="product-price">单价: ￥{{ order.product && order.product.price || 0 }}</div>
								<div class="product-tags" v-if="order.product">
									<el-tag size="mini" type="info" v-if="order.product.category">
										{{ order.product.category.name }}
									</el-tag>
									<el-tag size="mini" type="success" v-if="order.product.brand">
										{{ order.product.brand.name }}
									</el-tag>
								</div>
								<div class="product-meta">
									<div>数量: {{ order.quantity || 0 }}</div>
									<div v-if="order.skus && order.skus.length > 0">
										<div v-for="sku in order.skus" :key="sku.sku_id">
											{{ sku.sku_code }} - ￥{{ sku.sku_price }}
										</div>
									</div>
								</div>
							</div>
						</div>
						
						<!-- 订单信息 -->
						<div class="order-info">
							<div class="info-item">
								<span class="info-label">用户信息</span>
								<span class="info-value">{{ order.user && order.user.nickname || '未知用户' }}</span>
							</div>
							<div class="info-item">
								<span class="info-label">联系电话</span>
								<span class="info-value">{{ order.user && order.user.phone || '无联系方式' }}</span>
							</div>
							<div class="info-item" v-if="order.address">
								<span class="info-label">收货地址</span>
								<span class="info-value">{{ (order.address.provinceCityDistrict || '') + ' ' + (order.address.detailAddress || '') }}</span>
							</div>
							<div class="info-item">
								<span class="info-label">创建时间</span>
								<span class="info-value">{{ order.createdAt }}</span>
							</div>
						</div>
					</div>
					
					<!-- 订单底部 -->
					<div class="order-footer">
						<div class="order-total">
							总额: ￥{{ order.totalAmount || 0 }}
							<span v-if="order.coupon" style="font-size: 12px; color: #909399; margin-left: 8px;">
								(优惠券: {{ order.coupon.name }})
							</span>
						</div>
						<div class="order-actions">
							<el-button type="text" size="mini" @click="showDetail(order)">查看详情</el-button>
							<el-button type="text" size="mini" @click="updateStatus(order)" v-if="order.status !== 'completed'">更新状态</el-button>
						</div>
					</div>
				</div>
			</div>
			
			<!-- 分页 -->
			<div class="page-box">
				<el-pagination
					background
					@size-change="handleSizeChange"
					@current-change="handleCurrentChange"
					:current-page="p.pageNum"
					:page-sizes="[10, 20, 30, 40]"
					:page-size="p.pageSize"
					layout="total, sizes, prev, pager, next, jumper"
					:total="dataCount">
					></el-pagination>
			</div>
		</div>
		
		<script>
			
			// 配置axios默认值
			axios.defaults.baseURL = 'http://localhost:8080';
			
			var app = new Vue({
				el: '#app',
				data: {
					loading: false,
					p: {
						pageNum: 1,
						pageSize: 10,
						status: '',
						orderId: ''
					},
					dataList: [],
					dataCount: 0,
					tempStatus: '',
					baseImageUrl: 'http://8.134.184.130:8008/images/', // 基础图片URL
					// 状态选项与数据库enum保持一致
					statusOptions: [
						{ label: '待支付', value: 'pending' },
						{ label: '待发货', value: 'shipment' },
						{ label: '已发货', value: 'shipped' },
						{ label: '已取消', value: 'cancelled' },
						{ label: '已完成', value: 'completed' }
					],
					// 状态映射
					statusMap: {
						'待支付': 'pending',
						'待发货': 'shipment',
						'已发货': 'shipped',
						'已取消': 'danger',
						'已完成': 'completed'
					},
					// 状态样式
					statusClass: {
						'pending': 'warning',
						'shipment': 'info',
						'shipped': 'success',
						'cancelled': 'danger',
						'completed': 'success'
					}
				},
				methods: {
					// 查询
					search() {
						this.loading = true;
						const apiUrl = this.p.status ? '/order/getTotalStatus' : '/order/listOrder';
						const params = {
							pageNum: this.p.pageNum,
							pageSize: this.p.pageSize
						};
						
						if (this.p.status) {
							params.status = this.p.status;
						}
						
						axios.get(apiUrl, {
							params: params
						})
						.then(response => {
							if(response.data.code === 200) {
								this.dataList = response.data.data.list;
								this.dataCount = response.data.data.total;
							} else {
								this.$message({
									message: response.data.message || '获取数据失败',
									duration: 1500,
									type: 'error'
								});
							}
						})
						.catch(error => {
							console.error('Error:', error);
							this.$message({
								message: '获取数据失败',
								duration: 1500,
								type: 'error'
							});
						})
						.finally(() => {
							this.loading = false;
						});
					},
					
					// 格式化订单ID
					formatOrderId(id) {
						if (!id) return '';
						// 如果已经是ORDER格式，提取数字部分
						if (String(id).toUpperCase().startsWith('ORDER')) {
							return String(id).replace(/[^0-9]/g, '');
						}
						// 直接返回数字部分
						return String(id).replace(/[^0-9]/g, '');
					},

					// 格式化显示订单ID
					formatDisplayOrderId(id) {
						if (!id) return '';
						// 如果已经是ORDER格式，直接返回
						if (String(id).toUpperCase().startsWith('ORDER')) {
							return String(id).toUpperCase();
						}
						// 提取数字部分并格式化
						const numPart = String(id).replace(/[^0-9]/g, '');
						const paddedId = numPart.padStart(7, '0');
						return 'ORDER' + paddedId;
					},

					// 根据查询条件选择不同的API
					searchByIdAndStatus() {
						this.loading = true;
						// 如果ID和状态都存在，使用组合查询API
						if (this.p.orderId && this.p.status) {
							// 处理订单ID格式
							const numericId = this.formatOrderId(this.p.orderId);
							console.log('Numeric Order ID:', numericId);

							axios.get('/order/getOrderByIdAndStatus', {
								params: {
									pageNum: this.p.pageNum,
									pageSize: this.p.pageSize,
									orderId: numericId,
									status: this.p.status
								}
							})
							.then(response => {
								if(response.data.code === 200) {
									this.dataList = response.data.data.list;
									this.dataCount = response.data.data.total;
									
									if (this.dataList.length === 0) {
										this.$message({
											message: '未找到相关订单',
											duration: 1500,
											type: 'warning'
										});
									}
								} else {
									this.$message({
										message: response.data.message || '查询失败',
										duration: 1500,
										type: 'error'
									});
								}
							})
							.catch(error => {
								console.error('Error:', error);
								this.$message({
									message: '查询失败',
									duration: 1500,
									type: 'error'
								});
							})
							.finally(() => {
								this.loading = false;
							});
							return;
						}
						
						// 如果只有ID，使用ID查询API
						if (this.p.orderId) {
							// 处理订单ID格式
							const numericId = this.formatOrderId(this.p.orderId);
							console.log('Numeric Order ID:', numericId);

							axios.get('/order/getOrderById', {
								params: {
									id: numericId
								}
							})
							.then(response => {
								if(response.data.code === 200) {
									if (response.data.data) {
										this.dataList = [response.data.data];
										this.dataCount = 1;
									} else {
										this.dataList = [];
										this.dataCount = 0;
										this.$message({
											message: '未找到相关订单',
											duration: 1500,
											type: 'warning'
										});
									}
								} else {
									this.$message({
										message: response.data.message || '查询失败',
										duration: 1500,
										type: 'error'
									});
								}
							})
							.catch(error => {
								console.error('Error:', error);
								this.$message({
									message: '查询失败',
									duration: 1500,
									type: 'error'
								});
							})
							.finally(() => {
								this.loading = false;
							});
							return;
						}
						
						// 如果只有状态或都没有，使用普通查询
						this.search();
					},
					// 重置
					reset() {
						this.p.status = '';
						this.p.orderId = '';
						this.search();
					},
					// 获取状态文本
					getStatusText(status) {
						return this.statusOptions.find(option => option.value === status)?.label || status;
					},
					// 查看详情
					showDetail(row) {
						layer.open({
							type: 2,
							title: '订单详情',
							content: 'order-info.html?id=' + row.id,
							area: ['1000px', '600px']
						});
					},
					// 更新状态
					updateStatus(row) {
						// 获取当前状态的中文显示
						const currentStatusLabel = this.getStatusText(row.status);
						
						// 初始化临时状态
						this.tempStatus = '';
						
						const app = this;
						
						// 使用模板创建对话框
						this.$alert(`
							<div style="margin: 10px 0;">
								<p style="margin-bottom: 10px;">当前状态：${currentStatusLabel}</p>
								<div id="status-select"></div>
							</div>
						`, '更新订单状态', {
							dangerouslyUseHTMLString: true,
							showCancelButton: true,
							confirmButtonText: '确定',
							cancelButtonText: '取消',
							beforeClose: (action, instance, done) => {
								if (action === 'confirm') {
									if (!app.tempStatus) {
										this.$message.warning('请选择新状态');
										return;
									}

									// 如果状态没有改变，直接返回
									if (app.tempStatus === row.status) {
										this.$message.info('状态未改变');
										done();
										return;
									}

									// 创建 FormData 对象
									const params = new URLSearchParams();
									params.append('id', row.id);
									params.append('status', app.tempStatus);

									// 发送请求
									instance.confirmButtonLoading = true;
									axios.post('/order/updateOrder', params, {
										headers: {
											'Content-Type': 'application/x-www-form-urlencoded'
										}
									}).then(response => {
										instance.confirmButtonLoading = false;
										if (response.data.code === 200) {
											this.$message({
												type: 'success',
												message: '更新成功',
												duration: 2000
											});
											this.search(); // 刷新列表
											done();
										} else {
											this.$message.error(response.data.message || '更新失败');
										}
									}).catch(error => {
										instance.confirmButtonLoading = false;
										console.error('Error:', error);
										this.$message.error('更新失败：' + (error.response?.data?.message || error.message || '未知错误'));
									});
								} else {
									app.tempStatus = '';
									done();
								}
							}
						}).then(() => {
							this.tempStatus = '';
						}).catch(() => {
							this.tempStatus = '';
						});

						// 在下一个 tick 挂载选择器
						this.$nextTick(() => {
							new Vue({
								el: '#status-select',
								template: `
									<el-select v-model="status" placeholder="请选择新状态" style="width: 100%">
										<el-option
											v-for="option in options"
											:key="option.value"
											:label="option.label"
											:value="option.value"
											:disabled="isDisabled(option.value)">
										</el-option>
									</el-select>
								`,
								data: {
									status: '',
									options: app.statusOptions,
									currentStatus: row.status
								},
								methods: {
									isDisabled(value) {
										// 当前状态不能选择
										if (value === this.currentStatus) {
											return true;
										}
										// 已完成状态不能被选择为目标状态
										if (this.currentStatus === 'completed') {
											return true;
										}
										// 根据状态流转规则禁用选项
										const validNextStatuses = app.getValidNextStatuses(this.currentStatus);
										return !validNextStatuses.includes(value);
									}
								},
								watch: {
									status(val) {
										app.tempStatus = val;
									}
								}
							});
						});
					},

					// 获取当前状态可以转换的下一个状态列表
					getValidNextStatuses(currentStatus) {
						// 根据数据库enum定义的状态流转规则
						const statusFlow = {
							
							'pending': ['shipment'],  // 已支付可以变为待发货
							'shipment': ['shipped', 'completed', 'awaiting_review'], // 发货中可以变为已发货、已完成、待评价
							'shipped': ['completed', 'awaiting_review'],  // 已发货可以变为已完成、待评价
							'completed': [],  // 已完成不可更改
							'awaiting_review': ['completed'], // 待评价可以变为已完成
							'cancelled': [] // 已取消不可更改
						};
						return statusFlow[currentStatus] || [];
					},

					// 获取状态显示样式
					getStatusType(status) {
						return this.statusClass[status] || '';
					},

					// 获取完整图片URL
					getFullImageUrl(imageUrl) {
						if (!imageUrl) return '';
						// 如果URL已经以http://或https://开头，直接返回
						if (imageUrl.startsWith('http://') || imageUrl.startsWith('https://')) {
							return imageUrl;
						}
						// 移除开头的斜杠以避免双斜杠
						const cleanUrl = imageUrl.startsWith('/') ? imageUrl.substring(1) : imageUrl;
						return this.baseImageUrl + cleanUrl;
					},

					// 处理每页显示数量变化
					handleSizeChange(val) {
						this.p.pageSize = val;
						this.p.pageNum = 1; // 重置到第一页
						this.search();
					},
					
					// 处理当前页变化
					handleCurrentChange(val) {
						this.p.pageNum = val;
						this.search();
					}
				},
				created() {
					this.search();
				}
			})
		</script>
	</body>
</html>
